<?php
/**
 * Created by PhpStorm.
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 7/5/16
 * Time: 01:47
 */

namespace Home\Controller;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Common\Library\SendSMS;
use Home\Model\ConsumeHistoryModel;
use Home\Model\FinishModel;
use Think\Controller;
use Think\Log;

class XianxiaController extends Controller {

    const START_TIME = 9*60*60;
    const END_TIME = 19*60*60;

    public function __construct() {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    private function getInstallmentDetail($amount)
    {
        return D("CustomerBill")->getInstallmentDetail($amount);
    }
    
    public function createOrder(){
        try{
            $data = I('post.');

            if(!($res = M('Customer')->where(['id_num'=>$data['id_num']])->find())){
                $res = D("Customer")->getAddressById($data['id_num']);
                $data_cutomer = [
                    'add_time' => time(),
                    'status' => Constant::CUSTOMER_USE,
                    'mobile' => $data['mobile'],
                    'real_name' => $data['real_name'],
                    'id_num' => $data['id_num'],
                    'gender' => $res['sex'],
                    'birthday' => $res['birthday'],
                    'birthplace' => $res['area'],
                    'pay_pass' => get_enc_password($data['pay_pass']),
                    'amount' => $data['amount'],
					'company' => $data['company'],
					'office_tel' => $data['office_tel']
                ];
                if(false === ($customerId = M('Customer')->add($data_cutomer))){
                    BusinessException::throwException(Constant::FAILED);
                }
                Log::write("用户信息录入成功", "INFO");
            }else{
                $customerId = $res['id'];
                $data_cutomer = [
                    'id' => $customerId,
                    'amount' => $res['amount']+$data['amount']
                ];
                if(false === ($ins = M('Customer')->save($data_cutomer))){
                    BusinessException::throwException(Constant::FAILED);
                }
                Log::write("老用户{id}已录入{amount}分", "INFO");
            }

            Log::write("记录分期list数据：用户id=".$customerId, "INFO");
            $consumeData = [
                'amount' => $data['amount'],
                'consume_amount' => $data['amount'],
                'discount_first_order' => 0,
                'discount_full_amount' => 0,
                'discount_full_reduce' => 0,
                'discount_rebate_amount' => 0,
                'type' => Constant::PAY_TYPE_INSTALLMENT,
                'merchant_id' => $data['merchant_id'],
                'status' => ConsumeHistoryModel::STATUS_REVIEWED,
                'repayment_time' => get_repayment_time(1),
                'add_time' => strtotime($data['add_time']),
                'customer_id' => $customerId
            ];
            if (!($insertId = D('ConsumeHistory')->add($consumeData))) {
                BusinessException::throwException(Constant::FAILED);
            }
            if(false === M('Customer')->execute("UPDATE `customer` SET `order_count`=`order_count` + 1  WHERE  `id` = '".$customerId."'")){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            //计算分期本金和利息,单位分
            $installmentDetail = $this->getInstallmentDetail($data['amount']);
            $principal = $installmentDetail['principal'];
            $interest = $installmentDetail['interest'];
            //分期后当月账单待还金额
            $currentRepayment = $principal + $interest;

            //生成分期明细
            $installmentData = [];
            // $i 一定要从1开始(原因:分期付款下月才开始还)
            for ($i = 1; $i <= Constant::REPAY_TIMES; $i++) {
                $installmentData[] = [
                    'amount' => $currentRepayment,
                    'parent_id'=>$insertId,
                    'repayment_time' => get_repayment_time($i),
                    'add_time' => time()
                ];
            }

            Log::write("记录分期detail数据：parent_id=".$insertId, "INFO");
            if (!($installmentId = D('ConsumeInstallmentHistory')->addAll($installmentData))) {
                BusinessException::throwException(Constant::FAILED);
            }

            $data = [
                'repay_times'      => Constant::REPAY_TIMES,
                'repay_principal'  => $principal,
                'repay_interest'   => $interest,
                'repay_total'      => $currentRepayment
            ];

            $billModel = D("CustomerBill");
            if ($billModel->hasRecord($customerId, Constant::PAY_TYPE_INSTALLMENT)) {
                $billRet = $billModel->updateRepaymentAmount($customerId, $currentRepayment, Constant::PAY_TYPE_INSTALLMENT);
            } else {
                $customerBill = [
                    'customer_id' => $customerId,
                    'type' =>  Constant::PAY_TYPE_INSTALLMENT,
                    'repayment_amount' => $currentRepayment,
                    'bill_date' => date('Y-m', get_repayment_time(1)),
                    'add_time' => time()
                ];
                $billId = $billModel->add($customerBill);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 批量注册用户
     */
    public function register()
    {
        try {
            //检查该用户是否存在，不存在则创建用户，存在则直接上传通讯录
            $mobile = I('post.');
            $password = I('post.password', '518E6C76CAF51EB410CAAB3C21DEF1B4B3C07401', 'string');
            $customer_data = [];
            if(count($mobile)){
                foreach ($mobile as $k=>$v){
                    if(strlen($v) == 11){
                        $customer = M('Customer')->where(['mobile'=>$v])->find();
                        if(!$customer) {
                            $start_time = '2016-08-01 00:00:00';
                            $end_time = '2016-10-27 00:00:00';
                            $customer_data[] = array(
                                'mobile' => $v,
                                'pay_pass' => get_enc_password($password),
                                'password' => get_enc_password($password),
                                'type' => 3,  //用户类型： 1-买呗app 2-51短贷  3线下数据
                                'add_time' => $this->rand_time($start_time, $end_time)
                            );
                        }
                    }
                }

                $customerId = M('Customer')->addAll($customer_data);
                $ret = Constant::getReturn(Constant::SUCCESS);
            }
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    //先定义一个可以生成随机时间的函数
    function rand_time($start_date,$end_date)
    {
        //日期随机
        $start_date = strtotime($start_date);
        $end_date = strtotime($end_date);

        return mt_rand(XianxiaController::START_TIME, XianxiaController::END_TIME) +
        strtotime(date('Y-m-d', mt_rand($start_date,$end_date)));
    }

    public function bankCard()
    {
        try{
            $data = I('post.');
            $customer = M('Customer')->where(['mobile'=>$data['user_mobile'], 'type'=>'2'])->find();
            if($customer) {
                $card = M('CustomerBankInfo')->where(['customer_id'=>$customer['id']])->find();
                if(!$card){
                    //绑定银行卡
                    $bankInfo = array(
                        'customer_id' => $customer['id'],
                        'card_num' => $data['card_num'],
                        'card_user_name' => $customer['real_name'],
                        'reserved_mobile' => $data['user_mobile'],
                        'usr_busi_agreement_id' => '',
                        'usr_pay_agreement_id' => '',
                        'gate_id' => $data['bank_name'],
                        'bank_card_type' => 'DEBITCARD',
                        'add_time' => time(),
                    );
                    if (false === ($insBank = M('CustomerBankInfo')->add($bankInfo))) {
                        BusinessException::throwException(Constant::BAND_CARD_ADD_FAILED);
                    }
                    $ret = Constant::getReturn(Constant::SUCCESS);
                }else{
                    BusinessException::throwException(Constant::BAND_CARD_EXIST);
                }
            }else{
                BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
            }
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function TouziOrder(){
        try{
            $data = I('post.');

            $start_time = '2016-11-15 09:00:00';
            $end_time = '2016-11-30 19:00:00';
            $consumeData = [
                'amount' => $data['amount'],
                'consume_amount' => $data['amount'],
                'discount_first_order' => 0,
                'discount_full_amount' => 0,
                'discount_full_reduce' => 0,
                'discount_rebate_amount' => 0,
                'type' => 200,
                'merchant_id' => $data['merchant_id'],
                'status' => 1,
                'repayment_time' => get_repayment_time(1),
                'add_time' => $this->rand_time($start_time, $end_time),
                'customer_id' => $data['customer_id'],
                'repay_id' => 1,
                'payway' => 3
            ];
            if (!($insertId = D('ConsumeHistory')->add($consumeData))) {
                BusinessException::throwException(Constant::OUT_OF_RANGE);
            }

            //计算分期本金和利息,单位分
            $conf = M('SysInstallmentPlan')->where(['id'=>1])->find();
            $installmentDetail = D('Finish')->getInstallmentDetail($data['amount'], $conf);
            //分期后当月账单待还金额
            $currentRepayment = $installmentDetail['bill'];

            //生成分期明细
            $installmentData = [];
            // $i 一定要从1开始(原因:分期付款下月才开始还)
            for ($i = 1; $i <= $conf['repay_times']; $i++) {
                $installmentData[] = [
                    'amount' => $currentRepayment,
                    'parent_id'=>$insertId,
                    'repayment_time' => get_repayment_time($i),
                    'add_time' => $consumeData['add_time']
                ];
            }

            Log::write("记录分期detail数据：parent_id=".$insertId, "INFO");
            if (!($installmentId = D('ConsumeInstallmentHistory')->addAll($installmentData))) {
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function updateCustomerTime(){
        try {
            $data = I('post.');

            $start_time = '2016-10-01 09:00:00';
            $end_time = '2016-10-31 19:00:00';
            $upd_data = [
                'add_time' => $this->rand_time($start_time, $end_time)
            ];

            /*if(false === M('Customer')->where(['id' =>$data['id'], 'type'=>3])->save($upd_data)){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }*/
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['msg'] = 'UPDATE customer SET add_time='.$upd_data['add_time'].' WHERE id = '.$data['id'].' AND type=3';
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
}